<template>
	<div class="k-design-box">
		<div class="cp-pool">
			<!-- <h3>控件区</h3> -->
			<VueDraggable v-model="modelData" :sort="false" :group="{ name: 'groupA', pull: 'clone' }" :clone="cloneComponnent">
				<div class="cp" v-for="i in modelData">
					{{ i.title }}
				</div>
			</VueDraggable>
		</div>
		<div class="cp-design">
			<!-- <h3>设计区</h3> -->
			<div theme="dark" style="flex: 1; overflow-y: auto">
				<div class="ques-block">
					<h2 contenteditable="true" @blur="common.methods.dataChange($event, questionData, 'title')" class="trans-in">{{ questionData.title }}</h2>
					<h4 contenteditable="true" style="margin-top: 6px" @blur="common.methods.dataChange($event, questionData, 'description')" class="trans-in">{{ questionData.description }}</h4>
					<label>
						<input type="checkbox" v-model="questionData.scoreIs" />
						是否统计分数
					</label>
				</div>
				<VueDraggable :animation="50" v-model="questionData.children" ghost-class="dragging-item" :group="{ name: 'groupA', put: true }" :handle="'.ques-opt-title-ope .move'">
					<template v-if="questionData?.children && questionData?.children.length > 0">
						<component v-for="(element, index) in questionData.children" :data-id="element.id" :key="element.id" class="ques-block" @tip="tip" :class="{ 'active-item': activeComponentId === element.id }" :is="getComponentType(element.type)" :dataVal="element" :index="index" :tool="{ ids }" @click="setActiveComponent(element.id)" @remove="remove" :scoreIs="questionData.scoreIs === 1" />
					</template>
					<template v-else>
						<div class="ques-block">
							<div class="ques-opt-title-opt no-data">
								<span>请拖拽组件到此处</span>
							</div>
						</div>
					</template>
				</VueDraggable>
			</div>
		</div>
	</div>
</template>
<script setup>
import common from "./common.js";
import modelData from "./model.js";
import Ids from "../../common/ids.js";
import { VueDraggable } from "vue-draggable-plus";
import { defineAsyncComponent, ref, computed, onMounted, reactive } from "vue";

const ids = new Ids();

const RadioQuestion = defineAsyncComponent(() => import("./RadioQuestion.vue"));
const CheckboxQuestion = defineAsyncComponent(() => import("./CheckBoxQuestion.vue"));
const FillBlankQuestion = defineAsyncComponent(() => import("./FillBlankQuestion.vue"));
const HorzBlankQuestion = defineAsyncComponent(() => import("./HorzBlankQuestion.vue"));
const MatrixRadioQuestion = defineAsyncComponent(() => import("./MatrixRadioQuestion.vue"));
const MatrixCheckboxQuestion = defineAsyncComponent(() => import("./MatrixCheckboxQuestion.vue"));
const MatrixFillBlankQuestion = defineAsyncComponent(() => import("./MatrixFillBlankQuestion.vue"));

const activeComponentId = ref("");
// const questionData = reactive({ title: "问卷标题", description: "副标题", scoreIs: 1, children: [] });
const { data: questionData } = defineProps({
	data: Object
});

/**初始化组件的ID */
function initIds(d) {
	ids.initData(d);
}

//组件异常通知
function tip(d) {
	console.log(d.msg);
}

/**计算是否统计分数，将其转化成boolean类型 */
const scoreIs = computed(() => {
	return questionData.scoreIs == 1;
});

/**拖动组件到设计区会触发此方法，响应的数据便是最后的渲染数据 */
function cloneComponnent(d) {
	//赋值一个模板出来，不要修改模板
	const data = JSON.parse(JSON.stringify(d));

	data.id = ids.get();
	//如果问卷的scoreIs=1,这不允许拖拽填空题,横向填空题,矩阵填空题
	if (questionData.scoreIs === 1) {
		let type = data.type;
		if (type === "fillblank" || type === "horzblank" || type === "matrixfillblank") {
			tip({ msg: "问卷设置了自动评分，不允许添加填空题！" });
			return; // 阻止拖拽
		}
	}
	if (data.children) {
		freshChildrenId(data.children); // 生成新的 ID
	}
	//如果问卷的scoreIs=1,那么模板选项下的attribute分数为其下标
	if (questionData.scoreIs === 1) {
		if (data.children) {
			data.children.forEach((child, index) => {
				child.attribute.score = index; // 设置分数为下标
			});
		}
	}

	if (data.type === "horzblank") {
		// 处理横向填空题的特殊情况，每一个<span>都需要生成新的 ID
		let idsa = []; // 用于存储生成的 ID
		const content = data.attribute.content.replace(/data-id="[^"]+"/g, () => {
			const id = ids.get(); // 生成新的 ID
			idsa.push(id); // 将生成的 ID 存储到数组中
			return `data-id="${id}"`; // 生成新的 ID
		});
		data.attribute.content = content; // 更新内容
		// 更新 item 的属性
		data.children = idsa.map((id) => {
			return { id, attribute: {} }; // 生成新的 ID
		});
	}
	console.log(data);
	return data;
}

/**更新选项下的ID */
function freshChildrenId(children) {
	children.forEach((item) => {
		item.id = ids.get(); // 生成新的 ID
		if (item.children) {
			freshChildrenId(item.children); // 递归处理子元素
		}
	});
}

/**设置当前选中的事哪一个问题 */
function setActiveComponent(id) {
	activeComponentId.value = id;
}
/**移除问题 */
function remove(data) {
	questionData.children = questionData.children.filter((item) => item.id !== data.id); // 删除选中的组件
}
/**问题类型 */
function getComponentType(type) {
	switch (type) {
		case "checkbox":
			return CheckboxQuestion;
		case "radio":
			return RadioQuestion;
		case "fillblank":
			return FillBlankQuestion;
		case "horzblank":
			return HorzBlankQuestion;
		case "matrixradio":
			return MatrixRadioQuestion;
		case "matrixfillblank":
			return MatrixFillBlankQuestion;
		case "matrixcheckbox":
			return MatrixCheckboxQuestion;
		default:
			return "div";
	}
}

function getData() {
	// console.log(questionData);
	return questionData;
}
defineExpose({
	initIds,
	getData
});
</script>
